package cn.ds.assets.framework.mybatis.core.util;

import cn.ds.assets.framework.common.pojo.PageParam;
import cn.ds.assets.framework.common.pojo.PageResult;
import cn.ds.assets.framework.common.pojo.SortingField;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分页工具类
 *
 * @author yxc
 * @desc:
 * @date 2023-2023/6/30-30 16:42:22
 */
public class PageUtils {

    private PageUtils() {
    }

    /**
     * 设置分页
     *
     * @param pageParam
     * @param <T>
     * @return
     */
    public static <T> Page<T> startPage(PageParam pageParam) {
        return PageUtils.startPage(pageParam, null);
    }

    /**
     * 设置分页
     *
     * @param pageParam
     * @param sortingFields
     * @param <T>
     * @return
     */
    public static <T> Page<T> startPage(PageParam pageParam, Collection<SortingField> sortingFields) {
        // 1.设置分页参数(页码+页数)
        Page<T> page = new Page<>(pageParam.getPageNo(), pageParam.getPageSize());
        // 2.设置排序字段
        if (CollUtil.isNotEmpty(sortingFields)) {
            List<OrderItem> orderItems = sortingFields.stream()
                    .map(sortingField -> SortingField.ORDER_ASC.equals(sortingField.getOrder()) ? OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField()))
                    .collect(Collectors.toList());
            page.addOrder(orderItems);
        }
        return page;
    }

    /**
     * 设置分页结果
     *
     * @param page
     * @param <T>
     * @return
     */
    public static <T> PageResult<T> pageResult(IPage<T> page) {
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

}
